<template>
  <s-layout class="set-wrap" title="品牌列表" :bgStyle="{ color: '#f7f7f7' }">
    <!-- 商品列表 -->
    <view class="flex flex-col gap-3 p-4">
      <u-tabs :list="state.productCategory" :scrollable="true" v-model="state.productCategoryactive" @change="handleChange"></u-tabs>
      <s-empty v-if="state.goodsBrandList.length === 0" text="暂无商品" icon="/static/data-empty.png" />
      <!-- {{ state.goodsBrandList.length }} -->

      <view class="grid grid-cols-2 gap-4">
        <view
          class="goods-card overflow-hidden bg-white rounded-xl shadow-sm"
          :class="[item.selected && 'selected', item.selecting && 'animate-pulse', !item.selecting && 'hover-effect']"
          v-for="(item, index) in state.goodsBrandList"
          :key="index"
          @click="selectGoods(item)"
        >
          <!-- 商品图片 -->
          <view class="aspect-square image-container overflow-hidden relative">
            <image
              :src="item.image || '/static/logo@3x.png'"
              class="w-full h-full transition-transform duration-300"
              :class="item.selected ? 'scale-105' : 'scale-100'"
              mode="aspectFill"
            />
            <!-- 选中状态 -->
            <view
              class="check-icon flex absolute top-2 right-2 justify-center items-center w-6 h-6 rounded-full transition-all duration-300"
              :class="[item.selected ? 'bg-blue-500 scale-110 shadow-lg' : 'bg-gray-300 scale-100', item.justSelected && 'animate-bounce']"
            >
              <text class="text-xs text-white transition-opacity duration-200" :class="item.selected ? 'opacity-100' : 'opacity-0'"> ✓ </text>
            </view>
            <!-- 选中遮罩 -->
            <view class="absolute inset-0 bg-blue-500 transition-opacity duration-300" :class="item.selected ? 'opacity-20' : 'opacity-0'"></view>
          </view>

          <!-- 商品信息 -->
          <view class="p-3 transition-all duration-300" :class="item.selected ? 'bg-blue-50' : 'bg-white'">
            <!-- 商品名称 -->
            <view
              class="line-clamp-2 mb-1 text-sm font-medium transition-colors duration-200"
              :class="item.selected ? 'text-blue-800' : 'text-gray-800'"
            >
              {{ item.brand_name || '商品名称' }}
            </view>

            <!-- 商品品牌 -->
            <view class="mb-2 text-xs transition-colors duration-200" :class="item.selected ? 'text-blue-600' : 'text-gray-500'">
              {{ item.title || '品牌名称' }}
            </view>

            <!-- 商品价格 -->
            <view class="flex justify-between items-center w-full">
              <view class="flex justify-between items-baseline w-full">
                <text
                  class="text-lg font-bold transition-all duration-200"
                  :class="[!item.selected ? 'text-red-500 scale-100' : 'text-blue-600 scale-105']"
                >
                  ¥{{ item.price || '0.00' }}
                </text>
                <text
                  class="ml-1 text-xs line-through transition-colors duration-200"
                  :class="item.selected ? 'text-blue-400' : 'text-gray-400'"
                  v-if="item.cost_price"
                >
                  ¥{{ item.cost_price }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <!-- <view class="animate-fade-in flex justify-center items-center py-6" v-if="state.loading">
        <view class="loading-spinner mr-2"></view>
        <text class="text-gray-500 animate-pulse">加载中...</text>
      </view> -->

      <!-- 没有更多 -->
      <!-- <view class="animate-fade-in flex justify-center items-center py-6" v-if="!state.hasMore && state.goodsBrandList.length > 0">
        <text class="animate-bounce-slow text-gray-400">没有更多商品了</text>
      </view> -->
    </view>

    <view class="py-20"></view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar fixed right-0 bottom-0 left-0 p-4 bg-white border-t border-gray-100">
      <view class="flex justify-between items-center mb-3">
        <view class="text-sm text-gray-600 transition-all duration-300">
          已选择
          <text class="font-medium transition-all duration-300" :class="[selectedCount > 0 ? 'text-blue-500 scale-110' : 'text-gray-400 scale-100']">
            {{ selectedCount > 0 ? '1' : '0' }}
          </text>
          件商品
        </view>
        <view
          class="clear-btn text-sm transition-all duration-200"
          :class="[selectedCount > 0 ? 'text-gray-600 cursor-pointer' : 'text-gray-400 cursor-not-allowed']"
          @click="clearSelection"
        >
          清空选择
        </view>
      </view>

      <view class="flex gap-3">
        <view
          class="confirm-btn grid flex-1 place-items-center py-3 rounded-lg transition-all duration-300"
          :class="[selectedCount > 0 ? 'bg-blue-500 shadow-lg transform-gpu' : 'bg-gray-300 shadow-none']"
          @click="confirmAdd"
        >
          <view class="font-medium text-white transition-all duration-200" :class="selectedCount > 0 ? 'scale-100' : 'scale-95'"> 确认添加 </view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
  import sheep from '@/sheep';
  const state = ref({
    productCategory: [],
    productCategoryactive: 0,
    productCategoryid: '',
    loading: false,
    goodsBrandList: [],
    page: 1,
    hasMore: true,
  });

  // 下拉加载更多

  onReachBottom((e) => {
    if (!state.value.hasMore) return;
    state.value.page++;
    goodsBrand();
  });
  goodscategory();
  function goodscategory() {
    let obj = {};
    sheep.$api.yy.goodscategory(obj).then((res) => {
      if (res.code === 1) {
        state.value.productCategory = res.data;
        state.value.productCategoryid = res.data[0].id;
        // goodsList();
        goodsBrand();
      }
    });
  }

  // 计算选中商品数量
  const selectedCount = computed(() => {
    return state.value.goodsBrandList.filter((item) => item.selected).length;
  });

  // 选择商品（单选模式）
  const selectGoods = (item) => {
    // 添加选择动画状态
    item.selecting = true;

    setTimeout(() => {
      const wasSelected = item.selected;

      // 先取消所有选中状态
      state.value.goodsBrandList.forEach((goodsItem) => {
        if (goodsItem !== item && goodsItem.selected) {
          goodsItem.selected = false;
          goodsItem.justSelected = false;
        }
      });

      // 设置当前项的选中状态
      item.selected = !wasSelected;

      // 如果是新选中，添加弹跳动画
      if (!wasSelected && item.selected) {
        item.justSelected = true;
        setTimeout(() => {
          item.justSelected = false;
        }, 600);
      }

      item.selecting = false;
    }, 150);
  };

  // 清空选择
  const clearSelection = () => {
    if (selectedCount.value === 0) return;

    // 添加清空动画
    state.value.goodsBrandList.forEach((item, index) => {
      if (item.selected) {
        setTimeout(() => {
          item.selected = false;
          item.justSelected = false;
        }, index * 50); // 错开动画时间
      }
    });
  };

  // 确认添加
  const confirmAdd = () => {
    const selected = state.value.goodsBrandList.filter((item) => item.selected);
    if (selected.length === 0) {
      uni.showToast({
        title: '请先选择商品',
        icon: 'none',
      });
      return;
    }

    uni.showModal({
      title: '确认添加',
      content: `确定要添加该商品吗？`,
      success: (res) => {
        if (res.confirm) {
          // 调用添加商品API
          addSelectedGoods(selected);
        }
      },
    });
  };

  // 添加选中商品
  const addSelectedGoods = (goods) => {
    console.log('goods==> ', goods);

    let obj = {
      id: goods[0].id,
    };
    sheep.$api.yy.goodsAdds(obj).then((res) => {
      clearSelection();
      state.value.page = 1;
      state.value.goodsBrandList = [];
      goodsBrand();
      uni.hideLoading();
      uni.showToast({
        title: '添加成功',
        icon: 'success',
      });
    });
  };

  // 获取商品品牌列表
  function goodsBrand() {
    state.value.loading = true;

    let obj = {
      page: state.value.page,
      category_id: state.value.productCategoryid,
    };
    sheep.$api.yy.goodsBrand(obj).then((res) => {
      console.log('🚀 ~ goodsBrand ~ res:', res);
      if (!res.data.data.length) {
        state.value.hasMore = false;
      }
      state.value.goodsBrandList = [...state.value.goodsBrandList, ...res.data.data];
    });
  }

  // 上拉加载更多
  onReachBottom(() => {
    if (!state.value.loading && state.value.hasMore) {
      state.value.page++;
      goodsBrand();
    }
  });
  function handleChange(item) {
    state.value.productCategoryid = item.id;
    state.value.page = 1;
    state.value.goodsBrandList = [];
    goodsBrand();
  }
</script>

<style lang="scss" scoped>
  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  // 自定义滚动条样式
  :deep(.uni-scroll-view) {
    &::-webkit-scrollbar {
      display: none;
    }
  }
</style>
